const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');

const userRouter = require('./router/user');

const app = express();

const server  = require('http').Server(app);
const io = require('socket.io')(server);

const model = require('./db');
const Chat = model.getModel('chat');


io.on('connection', function(socket) {
    socket.on('sendChat', function(data) {
        const { from, to, msg } = data;
        const chatid = [from, to].sort().join('_');
        Chat.create({chatid, from, to, content: msg, create_time: new Date().getTime()}, function(err, doc) {
            io.emit('recvMsg', Object.assign({}, doc._doc));
        });
    });
})


app.use(cookieParser());
app.use(bodyParser.json());
app.use('/user',userRouter);

server.listen(9093, function(){
	console.log('test node app start at port 9093')
})